#include "../src/server.hpp"

EventLoop base_loop;
LoopThreadPool* looppool = nullptr;
uint64_t conn_id = 1;

void OnMessage(const PtrConnection& conn, Buffer* buffer)
{
    DBG_LOG("buffer: %s", buffer->ReadPosition());
    buffer->MoveReadOffset(buffer->ReadAbleSize());
    std::string str = "hello world!";
    conn->Send(str.c_str(), str.size());
    conn->ShutDown();
}
std::unordered_map<uint64_t, PtrConnection> conns;
void ConnectionDestory(const PtrConnection& conn)
{
    conns.erase(conn->Id());
}
void OnConnected(const PtrConnection& conn)
{
    DBG_LOG("new connection: %p", conn.get());
}
void Accept(int new_sockfd)
{
    /* 为新连接创建Channel并添加事件监控 */
    PtrConnection conn(new Connection(looppool->NextLoop(), conn_id, new_sockfd));
    conn->SetSvrCloseCallback(std::bind(ConnectionDestory, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->EnableInactiveRelease(10);// 启动非活跃连接超时销毁
    conn->Established();// 连接初始化

    conns.insert(std::make_pair(conn_id, conn));

    ++conn_id;
    DBG_LOG("principal thread");
}

int main()
{
    looppool = new LoopThreadPool(&base_loop);
    looppool->SetThreadCount(2);
    looppool->Create();

    Acceptor acceptor(&base_loop, 9000);
    // 监听套接字只需要获取新连接一个功能，因此只需要监听读事件
    acceptor.SetAcceptCallback(std::bind(Accept, std::placeholders::_1)); // 在回调函数中获取新连接，为新连接创建Channel并添加事件监控
    acceptor.Listen();// 启动监听套接字上的读事件监控

    base_loop.Start();
    // while (true)
    // {
    //     // sleep(1);
    //     // 获取新连接
    //     int sockfd = listen_sock.Accept();
    //     if (sockfd < 0)
    //         continue;

    //     Socket client_sock(sockfd);
    //     char buffer[1024] = {0};
    //     int ret = client_sock.Recv(buffer, 1023);
    //     if (ret < 0)
    //     {
    //         client_sock.Close();
    //         continue;
    //     }
    //     client_sock.Send(buffer, ret);
    //     client_sock.Close();
    // }
    
    return 0;
}